package com.retailshop.shopcontrol.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.retailshop.shopcontrol.common.HttpPost;
import com.retailshop.shopcontrol.common.MessageConstants;
import com.retailshop.shopcontrol.common.Response;
import com.retailshop.shopcontrol.entity.HttpRequestConfig;
import com.retailshop.shopcontrol.entity.PostJson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class AdminController {

    /**
     * 管理员模块
     * 创建日期:2018年4月6日
     * 功能描述:通过request的方式来获取到json数据
     *
     * @param jsonobject 这个是阿里的 fastjson对象
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/adminjson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String GetAdminJson(HttpServletRequest request, @RequestBody JSONObject jsonParam) {
        try {
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());

            //将接收到的数据转化为对象
            PostJson postJson = JSON.parseObject(jsonParam.toJSONString(), new TypeReference<PostJson>() {
            });
            String url = postJson.getUrl();
            //请求参数
            String parm = postJson.getParm();
            if(url.isEmpty() || parm.isEmpty())
            {
                return "{\"code\":999999,\"msg\":\"参数错误\",\"errorDetail\":\"参数错误\",\"count\":0,\"data\":[]}";
            }
            else
            {
                return GetAdminMod(request,url,parm);
            }
        } catch (Exception ex) {
            return "{\"code\":999999,\"msg\":\"访问错误\",\"errorDetail\":\""+ex.getMessage()+"\",\"count\":0,\"data\":[]}";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/admin")
    public String GetAdmin(HttpServletRequest request) {
        try {

            //请求地址
            String url=request.getParameter("url");
            //请求参数
            String parm="";

            //读取所有参数
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if(!paramName.equals("url"))
                {
                    parm +=",\""+paramName+"\":\""+request.getParameter(paramName)+"\"";
                }
            }

            if(url.isEmpty() || url=="")
            {
                return "{\"code\":999999,\"msg\":\"参数错误\",\"errorDetail\":\"参数错误\",\"count\":0,\"data\":[]}";
            }
            else
            {
                if(parm.length()>1)
                {
                    parm = parm.substring(1);
                }
                parm ="{"+parm+"}";
                return GetAdminMod(request,url,parm);
            }
        } catch (Exception ex) {
            return "{\"code\":999999,\"msg\":\"访问错误\",\"errorDetail\":\""+ex.getMessage()+"\",\"count\":0,\"data\":[]}";
        }
    }

    public String GetAdminMod(HttpServletRequest request, String url, String parm) {
        //模块URL
        String modUrl = HttpRequestConfig.userServerUrl;
        //模块密钥
        String modKey = "63cca9daa815b390f62f35f92e4d5392";

        return HttpPost.GetMod(request,modUrl,modKey,url,parm);
    }

    @ResponseBody
    @RequestMapping(value = "/Adminlogin")
    public Response GetAdmin(@RequestParam Map<String, String> map, HttpServletRequest request) {

        String username = map.get("username");
        String password = map.get("password");
        if (username.isEmpty() && password.isEmpty()) {
            return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "", request);
        } else {
            //请求参数
            String parm="";
            parm +=",\"us\":\""+username+"\"";
            parm +=",\"pwd\":\""+password+"\"";
            //parm +=",\"state\":\""+1+"\"";
            if(parm.length()>1)
            {
                parm = parm.substring(1);
            }
            parm ="{"+parm+"}";
            String res =GetAdminMod(request,"Admin/Self",parm);
            System.out.println(res);
            JSONObject resJSON = JSONObject.parseObject(res);
            String msgCode = resJSON.get("code").toString();
            if (msgCode.equals("000000")) {//如果失败
                boolean state = Boolean.parseBoolean(resJSON.getJSONObject("data").get("state").toString());
                if(state) {
                    String us = resJSON.getJSONObject("data").get("us").toString();
                    String id = resJSON.getJSONObject("data").get("id").toString();
                    String name = resJSON.getJSONObject("data").get("name").toString();
                    String role = resJSON.getJSONObject("data").get("role").toString();
                    //Session
                    HttpSession httpSession = request.getSession();
                    httpSession.setAttribute("us", us);
                    httpSession.setAttribute("name", name);
                    httpSession.setAttribute("role", role);
                    httpSession.setAttribute("id", id);
                    return new Response(MessageConstants.MSG_SUCCESS, role, 0, "", request);
                }
                else
                {
                    return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "用户被锁定，请联系管理员!!", request);
                }
            }
            else {
                return new Response(MessageConstants.MSG_INVALID_LOGIN, null, 0, "编号或者密码错误!!", request);

            }
        }
    }

}
